<?php

namespace yifang\exception;

use yifang\App;
use Throwable;
use Exception;
use yifang\response\Response;

class Handle
{
    /** @var App */
    protected $app;

    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
    ];

    protected $isJson = false;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    /**
     * 报告或记录异常。
     */
    public function report(Throwable $exception)
    {
        if (!$this->isIgnoreReport($exception)) {
            // 收集异常数据
            if ($this->app->isDebug()) {
                $data = [
                    'file'    => $exception->getFile(),
                    'line'    => $exception->getLine(),
                    'message' => $this->getMessage($exception),
                    'code'    => $this->getCode($exception),
                ];
                $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";
            } else {
                $data = [
                    'code'    => $this->getCode($exception),
                    'message' => $this->getMessage($exception),
                ];
                $log = "[{$data['code']}]{$data['message']}";
            }
            if ($this->app->config->get('log.record_trace')) {
                $log .= PHP_EOL . $exception->getTraceAsString();
            }
            try {
                $this->app->log->record($log, 'error');
            } catch (Exception $e) {}
        }
    }

    /**
     * 是忽略报告
     */
    protected function isIgnoreReport(Throwable $exception)
    {
        foreach ($this->ignoreReport as $class) {
            if ($exception instanceof $class) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将异常呈现到HTTP响应中。
     */
    public function render($request, Throwable $e)
    {
        $this->isJson = $request->isJson();
        $isAjax=$request->isAjax();
        if($isAjax){
            $this->isJson=true;
        }
        ob_end_clean();
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof HttpException) {
            return $this->renderHttpException($e);
        } else {
            return $this->convertExceptionToResponse($e);
        }
    }

    /**
     * 渲染http异常
     */
    protected function renderHttpException(HttpException $e)
    {
        $status   = $e->getStatusCode();
        $template = $this->app->config->get('app.http_exception_template');
        if (!$this->app->isDebug() && !empty($template[$status]) && !$this->isJson) {
            return Response::create($template[$status], 'view', $status)->assign(['e' => $e]);
        } else {
            return $this->convertExceptionToResponse($e);
        }
    }

    /**
     * 收集异常数据
     */
    protected function convertExceptionToArray(Throwable $exception)
    {
        if ($this->app->isDebug()) {
            // 调试模式，获取详细的错误信息
            $traces        = [];
            $nextException = $exception;
            do {
                $traces[] = [
                    'name'    => get_class($nextException),
                    'file'    => $nextException->getFile(),
                    'line'    => $nextException->getLine(),
                    'code'    => $this->getCode($nextException),
                    'message' => $this->getMessage($nextException),
                    'trace'   => $nextException->getTrace(),
                    'source'  => $this->getSourceCode($nextException),
                ];
            } while ($nextException = $nextException->getPrevious());
            $data = [
                'code'    => $this->getCode($exception),
                'message' => $this->getMessage($exception),
                'traces'  => $traces,
                'datas'   => $this->getExtendData($exception),
                'tables'  => [
                    'GET Data'            => $this->app->request->get(),
                    'POST Data'           => $this->app->request->post(),
                    'Files'               => $this->app->request->file(),
                    'Cookies'             => $this->app->request->cookie(),
                    'Session'             => session()->all(),
                    'Server/Request Data' => $this->app->request->server(),
                ],
            ];
        } else {
            // 部署模式仅显示 Code 和 Message
            $data = [
                'code'    => $this->getCode($exception),
                'message' => $this->getMessage($exception),
            ];
            if (!$this->app->config->get('app.show_error_msg')) {
                // 不显示详细错误信息
                $data['message'] = $this->app->config->get('app.error_message');
            }
        }
        return $data;
    }

    /**
     * 转换异常信息到响应对象
     */
    protected function convertExceptionToResponse(Throwable $exception)
    {
        if (!$this->isJson) {
            $response = Response::create($this->renderExceptionContent($exception));
        } else {
            $response = Response::create($this->convertExceptionToArray($exception), 'json');
        }
        if ($exception instanceof HttpException) {
            $statusCode = $exception->getStatusCode();
            $response->header($exception->getHeaders());
        }
        return $response->code($statusCode ?? 500);
    }

    protected function renderTimeoutExceptionContent()
    {
        ob_start();
        $data = array(
            "code"=>"1",
            "message"=>"运行超时",
        );
        extract($data);
        include $this->app->config->get('app.exception_html') ?: YIFANG_PATH . '/tpl/exception.php';
        return ob_get_clean();
    }

    protected function renderExceptionContent(Throwable $exception)
    {
        ob_start();
        $data = $this->convertExceptionToArray($exception);
        extract($data);
        include $this->app->config->get('app.exception_html') ?: YIFANG_PATH . '/tpl/exception.php';
        return ob_get_clean();
    }

    /**
     * 获取错误编码
     */
    protected function getCode(Throwable $exception)
    {
        $code = $exception->getCode();
        if (!$code && $exception instanceof ErrorException) {
            $code = $exception->getSeverity();
        }
        return $code;
    }

    /**
     * 获取错误信息
     */
    protected function getMessage(Throwable $exception)
    {
        $message = $exception->getMessage();
        if ($this->app->runningInConsole()) {
            return $message;
        }
        $lang = $this->app->lang;
        if (strpos($message, ':')) {
            $name    = strstr($message, ':', true);
            $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message;
        } elseif (strpos($message, ',')) {
            $name    = strstr($message, ',', true);
            $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message;
        } elseif ($lang->has($message)) {
            $message = $lang->get($message);
        }
        return $message;
    }

    /**
     * 获取出错文件内容
     */
    protected function getSourceCode(Throwable $exception)
    {
        // 读取前9行和后9行
        $line  = $exception->getLine();
        $first = ($line - 9 > 0) ? $line - 9 : 1;
        try {
            $contents = file($exception->getFile()) ?: [];
            $source   = [
                'first'  => $first,
                'source' => array_slice($contents, $first - 1, 19),
            ];
        } catch (Exception $e) {
            $source = [];
        }
        return $source;
    }

    /**
     * 获取异常扩展信息
     */
    protected function getExtendData(Throwable $exception)
    {
        $data = [];
        if ($exception instanceof \yifang\lib\Exception) {
            $data = $exception->getData();
        }
        return $data;
    }

    /**
     * 获取常量列表
     */
    protected function getConst()
    {
        $const = get_defined_constants(true);
        return $const['user'] ?? [];
    }
}